package com.yzz.hzraisedust.hzraseidust.main.squaredetail;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.yzz.hzraisedust.hzraseidust.R;
import com.yzz.hzraisedust.hzraseidust.main.BaseActivity;
import com.yzz.hzraisedust.hzraseidust.modelbean.PmDetailItemBean;
import com.yzz.hzraisedust.hzraseidust.modelbean.PmItemBean;
import com.yzz.hzraisedust.hzraseidust.modelbean.ProjectAlarmdetailBean;
import com.yzz.hzraisedust.hzraseidust.modelbean.SquareDetailItemBean;
import com.yzz.hzraisedust.hzraseidust.util.Constant;
import com.yzz.hzraisedust.hzraseidust.util.JsonUtil;
import com.yzz.hzraisedust.hzraseidust.util.NetUtil;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.LineChartView;

public class ProjectAlarmDetailActivity extends BaseActivity implements Response.Listener<String>,Response.ErrorListener{

    private List<Item> items;
    private ListView mListView;
    private TextView mTitleView;
    private LineChartView mLineCharView;

    private ProjectAlarmdetailBean mPmdetailItem;

    private List<PointValue> mPointValues = new ArrayList<PointValue>();
    private List<AxisValue> mAxisXValues = new ArrayList<AxisValue>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_project_alarm_detail);
        initLoginingDlg();
        showLoginingDlg();
        initView();
        initData();
    }

    private void initView() {
        mListView = findViewById(R.id.project_detail_listview);
        TextView textView = findViewById(R.id.project_detail_list_empty_textview);
        mListView.setEmptyView(textView);
        View include = findViewById(R.id.back_to_pri_include);
        mTitleView = include.findViewById(R.id.title_all_textview);
        ImageView back = include.findViewById(R.id.back_to_pri_imageview);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        mLineCharView = findViewById(R.id.project_alarm_pm_line_char_view);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void initData(){
        SquareDetailItemBean item = (SquareDetailItemBean)getIntent().getSerializableExtra(Constant.ALARM_PROJECT_ITEM_BEAN);
        mTitleView.setText(item.getName());
        NetUtil netUtil = new NetUtil(ProjectAlarmDetailActivity.this);
        Map<String,String> params = new HashMap<>();
        params.put(Constant.UID_LOWER_KEY,Constant.Uid);
        params.put(Constant.SN_LOWER_KEY,item.getSN());
        netUtil.requestData(this,this,Constant.ALARM_PROJECT_URL,params);
    }
    private int maxValue = 500;
    /**
     * 设置X 轴的显示
     */
    private void getAxisXLables(){
        for (int i = 0; i < mPmdetailItem.getHistoryList().size(); i++) {
            PmItemBean item = mPmdetailItem.getHistoryList().get(i);
            if(item.getPm10()>maxValue){
                maxValue = item.getPm10();
            }
            mAxisXValues.add(new AxisValue(i).setLabel(""));
        }
    }

    /**
     * 图表的每个点的显示
     */
    private void getAxisPoints(){
        for (int i = 0; i < mPmdetailItem.getHistoryList().size(); i++) {
            mPointValues.add(new PointValue(i, mPmdetailItem.getHistoryList().get(i).getPm10()));
        }
    }
    private void initLineChart(){
        Line line = new Line(mPointValues).setColor(Color.parseColor("#FFCD41"));  //折线的颜色（橙色）

        List<Line> lines = new ArrayList<Line>();
        line.setShape(ValueShape.CIRCLE);//折线图上每个数据点的形状  这里是圆形 （有三种 ：ValueShape.SQUARE  ValueShape.CIRCLE  ValueShape.DIAMOND）
        line.setCubic(true);//曲线是否平滑，即是曲线还是折线
        line.setFilled(false);//是否填充曲线的面积
        line.setHasLabels(true);//曲线的数据坐标是否加上备注
//      line.setHasLabelsOnlyForSelected(true);//点击数据坐标提示数据（设置了这个line.setHasLabels(true);就无效）
        line.setHasLines(true);//是否用线显示。如果为false 则没有曲线只有点显示
        line.setHasPoints(false);//是否显示圆点 如果为false 则没有原点只有点显示（每个数据点都是个大的圆点）
        lines.add(line);
        LineChartData data = new LineChartData();
        data.setLines(lines);

        //坐标轴
        Axis axisX = new Axis(); //X轴
        axisX.setHasTiltedLabels(true);  //X坐标轴字体是斜的显示还是直的，true是斜的显示
        axisX.setTextColor(Color.BLACK);  //设置字体颜色
        //axisX.setName("date");  //表格名称
        axisX.setTextSize(10);//设置字体大小
        axisX.setMaxLabelChars(8); //最多几个X轴坐标，意思就是你的缩放让X轴上数据的个数7<=x<=mAxisXValues.length
        axisX.setValues(mAxisXValues);  //填充X轴的坐标名称
        data.setAxisXBottom(axisX); //x 轴在底部
        //data.setAxisXTop(axisX);  //x 轴在顶部
        axisX.setHasLines(true); //x 轴分割线

        // Y轴是根据数据的大小自动设置Y轴上限(在下面我会给出固定Y轴数据个数的解决方案)
        Axis axisY = new Axis();  //Y轴
        axisY.setName("");//y轴标注
        axisY.setTextSize(10);//设置字体大小
        data.setAxisYLeft(axisY);  //Y轴设置在左边

        //data.setAxisYRight(axisY);  //y轴设置在右边


        //设置行为属性，支持缩放、滑动以及平移
        mLineCharView.setInteractive(true);
        // mLineCharView.setZoomType(ZoomType.HORIZONTAL);
        //  mLineCharView.setMaxZoom((float) 2);//最大方法比例
        //  mLineCharView.setContainerScrollEnabled(true, ContainerScrollType.HORIZONTAL);
        mLineCharView.setLineChartData(data);
        mLineCharView.setVisibility(View.VISIBLE);
        /**注：下面的7，10只是代表一个数字去类比而已
         * 当时是为了解决X轴固定数据个数。见（http://forum.xda-developers.com/tools/programming/library-hellocharts-charting-library-t2904456/page2）;
         */
        Viewport v = new Viewport(mLineCharView.getMaximumViewport());v.bottom = 0;
        v.bottom = 0;
        v.top = maxValue;
        mLineCharView.setMaximumViewport(v);
        v.left = 0;
        v.right=mPmdetailItem.getHistoryList().size()-1;
        mLineCharView.setCurrentViewport(v);
    }

    @Override
    public void onErrorResponse(VolleyError volleyError) {
        Toast.makeText(this,"发生错误",Toast.LENGTH_LONG).show();
        closeLoginingDlg();
        finish();
    }

    @Override
    public void onResponse(String s) {
        mPmdetailItem = (ProjectAlarmdetailBean)JsonUtil.jsonToObject(s, ProjectAlarmdetailBean.class);
        if(mPmdetailItem!=null && mPmdetailItem.isSuccess()) {
            updataView();
        }else{
            closeLoginingDlg();
            Toast.makeText(ProjectAlarmDetailActivity.this,"出现错误:"+mPmdetailItem.getMessage(),Toast.LENGTH_LONG).show();
        }
        closeLoginingDlg();
    }

    private void updataView() {
        updateListView();
        updateChartView();
    }
    private  void updateListView(){
        items = new ArrayList<>();
        Item item = new Item();
        item.Name ="监测点";
        item.Value = mPmdetailItem.getDeviceName();
        items.add(item);
        Item item1 = new Item();
        item1.Name ="施工单位";
        item1.Value = mPmdetailItem.getWorkName();
        items.add(item1);
        Item item2 = new Item();
        item2.Name ="预警时长";
        item2.Value = mPmdetailItem.getWarningTime();
        items.add(item2);
        Item item3 = new Item();
        item3.Name ="报警时长";
        item3.Value = mPmdetailItem.getAlarmTime();
        items.add(item3);
        Item item4 = new Item();
        item4.Name ="项目经理";
        item4.Value = mPmdetailItem.getProjectManager();
        items.add(item4);
        Item item5 = new Item();
        item5.Name ="所属区域";
        item5.Value = mPmdetailItem.getAreaName();
        items.add(item);
        PAdapter pAdapter = new PAdapter();
        mListView.setAdapter(pAdapter);
    }
    private  void updateChartView(){
        getAxisXLables();//获取x轴的标注
        getAxisPoints();//获取坐标点
        initLineChart();//初始化
    }


    class PAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return items.size();
        }

        @Override
        public Object getItem(int i) {
            return items.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder viewHolder = null;
            if(view == null){
                view = LayoutInflater.from(ProjectAlarmDetailActivity.this).inflate(R.layout.project_detail_item_value_layout,null,false);
                viewHolder = new ViewHolder();
                viewHolder.projectNameTextView = view.findViewById(R.id.project_detail_item_item_key_textview);
                viewHolder.alarmCountTextView = view.findViewById(R.id.project_detail_item_value_textview);
                view.setTag(viewHolder);
            }
            if(viewHolder == null){
                viewHolder = (ViewHolder) view.getTag();
            }
            Item item = items.get(i);
            viewHolder.projectNameTextView.setText(item.Name);
            String showValue  = item.Value;
            if(item.Name.equals("报警时长")||item.Name.equals("预警时长")) {
                int time = Integer.valueOf(showValue);
                int hour = time/60;
                int minite = time % 60;
                showValue = hour+"时"+minite+"分";
            }
            viewHolder.alarmCountTextView.setText(""+showValue);
            return view;
        }
        class ViewHolder{
            TextView projectNameTextView;
            TextView alarmCountTextView;
        }
    }

    class Item{
        String Name;
        String Value;
    }


}
